package com.xfc.config;

import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

/**
 * 工具类
 * @author lcj
 *
 */
public class Tools {

    //盐
    public static String SALT="%$Avc52#0.";

    //短信缓存目录
    public static String SMS_CODE="code:px";

    //用户缓存目录
    public static String USER_TOKEN="user:key_";

    //解密key
    public static String USER_KRY="@X2378SDHNWJdjnf";

    //解密key
    public static int SMS_NUM=20;


    /**
     * 获取用户token
     */
    public static String getToken(HttpServletRequest request){

        return request.getHeader("token");
    }



    /**
     * 获取uuid
     * @return
     */
    public static String getUuid(){
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 获取密码
     * @return
     */
    public static String getPassword(String password){
        password=password+SALT;
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }

    /**
     * 短信验证码
     * @return
     */
    public static String getCode() {
        return String.valueOf((Math.random()*9+1)*100000);
    }

    /**
     * 6位邀请码
     * @return
     */
    public static String getInvitationCode() {

        String a = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        char[] rands = new char[6];
        for (int i = 0; i < rands.length; i++)
        {
            int rand = (int) (Math.random() * a.length());
            rands[i] = a.charAt(rand);
        }
        return String.valueOf(rands);
    }

    /**
     * 获取年龄
     * @param birthday
     * @return
     */
    public static int getAgeByBirth(Date birthday){
        //Calendar：日历
        /*从Calendar对象中或得一个Date对象*/
        Calendar cal = Calendar.getInstance();
        /*把出生日期放入Calendar类型的bir对象中，进行Calendar和Date类型进行转换*/
        Calendar bir = Calendar.getInstance();
        bir.setTime(birthday);
        /*如果生日大于当前日期，则抛出异常：出生日期不能大于当前日期*/
        if(cal.before(birthday)){
            throw new IllegalArgumentException("The birthday is before Now,It's unbelievable");
        }
        /*取出当前年月日*/
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayNow = cal.get(Calendar.DAY_OF_MONTH);
        /*取出出生年月日*/
        int yearBirth = bir.get(Calendar.YEAR);
        int monthBirth = bir.get(Calendar.MONTH);
        int dayBirth = bir.get(Calendar.DAY_OF_MONTH);
        /*大概年龄是当前年减去出生年*/
        int age = yearNow - yearBirth;
        /*如果出当前月小与出生月，或者当前月等于出生月但是当前日小于出生日，那么年龄age就减一岁*/
        if(monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)){
            age--;
        }
        return age;
    }
}
